package com.piggy.logi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.exception.CustomException;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.logi.sys.api.domain.LogiSysDictData;
import com.piggy.logi.sys.api.domain.LogiSysDictType;
import com.piggy.logi.sys.mapper.LogiSysDictDataMapper;
import com.piggy.logi.sys.mapper.LogiSysDictTypeMapper;
import com.piggy.logi.sys.service.ILogiSysDictTypeService;
import com.rabbitmq.client.LongString;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author shark
 */
@Service
public class LogiSysDictTypeServiceImpl extends ServiceImpl<LogiSysDictTypeMapper, LogiSysDictType> implements ILogiSysDictTypeService {

    @Resource
    private LogiSysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    @Override
    public TableDataInfo<LogiSysDictType> selectPageDictTypeList(LogiSysDictType dictType) {
        return PageUtils.buildDataInfo(page(PageUtils.buildPage(), buildQuery(dictType)));
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<LogiSysDictType> selectDictTypeList(LogiSysDictType dictType) {
        Map<String, Object> params = dictType.getParams();
        return list(buildQuery(dictType));
    }

    private LambdaQueryWrapper<LogiSysDictType> buildQuery(LogiSysDictType dictType) {
        Map<String, Object> params = dictType.getParams();
        return new LambdaQueryWrapper<LogiSysDictType>()
                .like(StrUtil.isNotBlank(dictType.getDictName()), LogiSysDictType::getDictName, dictType.getDictName())
                .eq(StrUtil.isNotBlank(dictType.getStatus()), LogiSysDictType::getStatus, dictType.getStatus())
                .like(StrUtil.isNotBlank(dictType.getDictType()), LogiSysDictType::getDictType, dictType.getDictType())
                .in(LogiSysDictType::getDeptId, Lists.newArrayList(0, ObjectUtil.defaultIfNull(dictType.getDeptId(),0L)))
                .notInSql(ObjectUtil.isNotEmpty(dictType.getDeptId()) && dictType.getDeptId() > 0L, LogiSysDictType::getDictId,
                        String.format(" select dict_id from logi_sys_dict_type where dept_id=0 and dict_type in (select distinct dict_type from logi_sys_dict_type where dept_id=%d) ", dictType.getDeptId()))
                .apply(Validator.isNotEmpty(params.get("beginTime")),
                        "date_format(create_time,'%y%m%d') >= date_format({0},'%y%m%d')",
                        params.get("beginTime"))
                .apply(Validator.isNotEmpty(params.get("endTime")),
                        "date_format(create_time,'%y%m%d') <= date_format({0},'%y%m%d')",
                        params.get("endTime"));
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<LogiSysDictType> selectDictTypeAll(Long mainDeptId) {
        return selectDictTypeList((LogiSysDictType) new LogiSysDictType().setDeptId(mainDeptId));
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<LogiSysDictData> selectDictDataByType(Long mainDeptId, String dictType) {
		/*List<LogiSysDictData> dictDatas = CacheUtils.getCache(CacheKeyEnums.LogiSysDictType.getKey(dictType), new TypeReference<List<LogiSysDictData>>(){});
		if (CollUtil.isNotEmpty(dictDatas)) {
			return dictDatas;
		}*/
        List<LogiSysDictData> dictDatas = dictDataMapper.selectDictDataByType(mainDeptId, dictType);
        if (CollUtil.isNotEmpty(dictDatas)) {
            //CacheUtils.cache(dictDatas, CacheKeyEnums.LogiSysDictType.getKey(dictType));
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public LogiSysDictType selectDictTypeById(Long dictId) {
        return getById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public LogiSysDictType selectDictTypeByType(Long mainDeptId, String dictType) {
        return getOne(buildQuery(new LogiSysDictType().setDictType(dictType).setDeptId(mainDeptId)));
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            LogiSysDictType dictType = selectDictTypeById(dictId);
            if (dictDataMapper.selectCount(new LambdaQueryWrapper<LogiSysDictData>()
                    .eq(LogiSysDictData::getDictType, dictType.getDictType())) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            //CacheUtils.remove(CacheKeyEnums.LogiSysDictType.getKey(dictType.getDictType()));
        }
        baseMapper.deleteBatchIds(Arrays.asList(dictIds));
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
		/*List<LogiSysDictType> dictTypeList = list();
		for (LogiSysDictType dictType : dictTypeList) {
			List<LogiSysDictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
			//CacheUtils.cache(dictDatas, CacheKeyEnums.LogiSysDictType.getKey(dictType.getDictType()));
		}*/
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        //CacheUtils.remove(CacheKeyEnums.LogiSysDictType.getKey()+"*");
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDictType(LogiSysDictType dict) {
        int row = baseMapper.insert(dict);
        // 插入所有字典
        List<LogiSysDictData> dictList = dictDataMapper.selectDictDataByType(0L, dict.getDictType());
        if (CollUtil.isEmpty(dictList)) {
            return row;
        }
        dictList.stream().peek(t-> {
            t.setDeptId(dict.getDeptId());
            t.setDictType(dict.getDictType());
            t.setDictCode(null);
            t.setCreateTime(new Date());
        }).collect(Collectors.toList());
        dictDataMapper.insertBatch(dictList);
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(LogiSysDictType dict) {
        LogiSysDictType oldDict = getById(dict.getDictId());
        if (!oldDict.getDeptId().equals(dict.getDeptId())) {
            // 通用字典写入服务商配置
            // 新增字典类型
            LogiSysDictType newAdd = BeanUtil.toBean(oldDict, LogiSysDictType.class);
            insertDictType(newAdd.setDictId(null).setDeptId(dict.getDeptId()).setDictType(dict.getDictType()));
            return 1;
        }
        dictDataMapper.update(null, new LambdaUpdateWrapper<LogiSysDictData>()
                .set(LogiSysDictData::getDictType, dict.getDictType())
                .eq(LogiSysDictData::getDictType, oldDict.getDictType())
                .eq(LogiSysDictData::getDeptId, oldDict.getDeptId()));
        return baseMapper.updateById(dict);
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(LogiSysDictType dict) {
        long dictId = Validator.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        LogiSysDictType dictType = getOne(new LambdaQueryWrapper<LogiSysDictType>()
                .eq(LogiSysDictType::getDictType, dict.getDictType())
				.eq(ObjectUtil.isNotEmpty(dict.getDeptId()) && dict.getDeptId()>0L, LogiSysDictType::getDeptId, dict.getDeptId())
                .last("limit 1"));
        if (Validator.isNotNull(dictType) && dictType.getDictId() != dictId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
